/*
 * @Author: xuetao 3168581151@qq.com
 * @Date: 2025-02-25
 * @LastEditors: xuetao 3168581151@qq.com
 * @LastEditTime: 2025-02-25
 * @Description: 
 */
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:path_provider/path_provider.dart';
import 'package:gal/gal.dart';
import 'package:flutter/services.dart';
import 'package:chat_client/services/api_service.dart';

final ApiService apiService = ApiService.instance;

/// 统一权限检查与请求（相册权限）
Future<bool> _checkAndRequestGalleryPermission() async {
  try {
    //检查是否已有权限
    if (await Gal.hasAccess()) return true;
    // 请求权限
    await Gal.requestAccess();
    // 再次检查权限状态
    if (!await Gal.hasAccess()) {
      throw GalException(
        type: GalExceptionType.notSupportedFormat,
        platformException: PlatformException(
          code: 'PERMISSION_DENIED',
          message: '相册访问权限被拒绝',
        ),
        stackTrace: StackTrace.current,
      );
    }
    return true;
  } on PlatformException catch (e, stackTrace) {
    throw GalException(
      type: GalExceptionType.unexpected,
      platformException: e,
      stackTrace: stackTrace,
    );
  }
}

/// 保存本地图片到相册
Future<void> saveLocalImage(String filePath) async {
  final file = File(filePath);
  if (!await file.exists()) {
    throw IOException('文件不存在');
  }

  await _checkAndRequestGalleryPermission();
  await Gal.putImage(filePath, album: 'chat_client');
}

/// 保存网络图片到相册
Future<void> saveNetworkImage(
  String url,
  void Function(int count, int total)? onProgress,
) async {
  try {
    // 下载到临时文件
    final tempDir = await getTemporaryDirectory();
    final tempPath =
        '${tempDir.path}/${DateTime.now().millisecondsSinceEpoch}.jpg';
    await apiService.downloadFile(url, tempPath, onProgress);

    // 检查权限
    await _checkAndRequestGalleryPermission();
    // 保存到相册
    await Gal.putImage(tempPath, album: 'chat_client');

    // 确保清理临时文件

    final tempFile = File(tempPath);
    if (await tempFile.exists()) await tempFile.delete();
  } on ApiError catch (e) {
    rethrow;
  } on GalException catch (e) {
    throw IOException('保存失败');
  }
}

/// 下载大文件方法（非图片）
/// [url] 文件下载地址
/// [saveName] 自定义保存文件名（可选）
/// [onProgress] 下载进度回调（count: 已接收字节, total: 总字节）
Future<File> downloadLargeFile({
  required String url,
  String? saveName,
  void Function(int count, int total)? onProgress,
}) async {
  Directory saveDir;
  try {
    saveDir = await getApplicationDocumentsDirectory();
  } catch (e) {
    throw IOException('无法获取存储目录: $e');
  }

  final filename = saveName ?? 'file_${DateTime.now().millisecondsSinceEpoch}';
  final savePath = '${saveDir.path}/$filename';

  try {
    await apiService.downloadFile(url, savePath, onProgress);
    return File(savePath);
  } on DioException catch (e) {
    // 删除可能不完整的文件
    final file = File(savePath);
    if (await file.exists()) await file.delete();
    throw IOException('下载失败: ${e.type} - ${e.message}');
  }
}

// 自定义异常类
class IOException implements Exception {
  final String message;
  IOException(this.message);

  @override
  String toString() => 'IOException: $message';
}
